package controller;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Anagrafica;
import dbms.Postgres;

/**
 * Servlet implementation class QueryServlet
 */
@WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public QueryServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		Anagrafica a = new Anagrafica();
		Postgres p = Postgres.getInstance();
		ResultSet rs = p.getAnagraficaById(id);
		try {
			if (rs.next()) {
				a.setCogn(rs.getString("cognome"));
				a.setNome(rs.getString("nome"));
				a.setId(Integer.parseInt(rs.getString("id")));
				a.setInd(rs.getString("ind"));
				a.setSesso(rs.getString("sesso").charAt(0));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		request.getSession().setAttribute("anagrafica", a);
		response.sendRedirect("vis2.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Postgres p = Postgres.getInstance();
		ResultSet rs = p.getLine();
		Anagrafica a;
		List l = new ArrayList();
		try {
			while (rs.next()) {
				a = new Anagrafica();
				a.setCogn(rs.getString("cognome"));
				a.setNome(rs.getString("nome"));
				a.setId(Integer.parseInt(rs.getString("id")));
				a.setInd(rs.getString("ind"));
				a.setSesso(rs.getString("sesso").charAt(0));
				l.add(a);
			}

			request.getSession().setAttribute("dati", l);
			response.sendRedirect("vis.jsp");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			p.closeStatement();
		}
	}

}
